/*
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.plugin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Clinton Begin
 */
public class InterceptorChain {

    private final List<Interceptor> interceptors = new ArrayList<>();

    /**
     * 例如现在有拦截器 interceptor1,interceptor2
     * 遍历这两个,首先target = CachingExecutor
     * 第一次遍历  target = 经过interceptor1代理过后的CachingExecutor
     * 第二次     target = 经过interceptor2代理过后的（经过interceptor1代理过后的CachingExecutor）
     * 所以在后期调用也会遍历调用拦截器Plugin中的invoke方法
     *
     * @param target Executor
     * @return
     */
    public Object pluginAll(Object target) {
        // 循环遍历所有拦截器,开启套娃的代理模式
        for (Interceptor interceptor : interceptors) {
            // 给所有的拦截器创建代理对象
            target = interceptor.plugin(target);
        }
        return target;
    }

    public void addInterceptor(Interceptor interceptor) {
        interceptors.add(interceptor);
    }

    public List<Interceptor> getInterceptors() {
        return Collections.unmodifiableList(interceptors);
    }

}
